package me.huanmeng.heater.signalling;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONSupport;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import me.huanmeng.heater.Heater;
import me.huanmeng.heater.bot.MessageHelper;
import me.huanmeng.heater.sender.Channel;
import me.huanmeng.heater.sender.User;
import me.huanmeng.heater.signalling.extra.SignallingExtraData;
import me.huanmeng.heater.signalling.extra.data.message.Text;

/**
 * 2021/9/27<br>
 * Heater<br>
 *
 * @author huanmeng_qwq
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class SignallingData<T extends SignallingExtraData<?>> extends JSONSupport implements MessageHelper {
    protected ChannelType channel_type;
    protected int type;
    protected String target_id;
    protected String author_id;
    protected String content;
    /**
     * 获取额外数据
     */
    protected T extra;//其他信息 如guild信息
    protected String msg_id;
    protected long msg_timestamp;
    protected String nonce;
    protected int from_type;

    @Override
    public void parse(JSON value) {
        super.parse(value);
        final ExtraType extraType = ExtraType.get(value.getByPath("extra.type"), channel_type);
        if (extraType != null) {
            //noinspection unchecked
            this.extra = ((T) JSONUtil.toBean(value.getByPath("extra").toString(), extraType.getClazz()));
        } else {
            debug("Failed get extra type: ", value);
        }
    }

    public void execute() {
        if (extra == null) {
            return;
        }
        extra.execute();
        if (extra.getExtraType() != ExtraType.TEXT) {
            return;
        }
        if (!content.startsWith("/")) {
            return;
        }
        final User user = Heater.getUser(((Text) extra).getAuthor().getId());
        if (user == null) {
            return;
        }
        final String guild_id = getTarget_id();
        final Channel channel = Heater.getChannel(guild_id);
        Heater.executeCommand(user, channel, content);
    }

    @Override
    public JSONObject toJSON() {
        return super.toJSON();
    }

    @Override
    public String toJSONString() {
        return toJSON().toJSONString(Heater.getIndentFactor() * 2);
    }
}
